<template>
  <view class="container">
    <!-- 视频播放区域 -->
    <view class="video-container">
      <!-- 视频播放组件 - 新增加载状态和错误提示 -->
      <view v-if="isLoading" class="loading">视频加载中...</view>
      <view v-else-if="isError" class="error-tip">视频加载失败，请检查网络</view>
      <video 
        id="videoPlayer" 
        class="video-player" 
        :src="currentCourse.videoUrl" 
        type="application/x-mpegURL"
        controls 
        :show-center-play-btn="true" 
        :show-fullscreen-btn="true" 
        :show-play-btn="true" 
        :show-progress-bar="true"
        @timeupdate="handleTimeUpdate"
        @error="handleVideoError"
        @loadedmetadata="handleVideoLoaded"
      >
        <button class="go-signup" @click="handleSignup">去报名</button>
      </video>
    </view>

    <!-- 课程标题 -->
    <view class="course-title">{{ currentCourse.title }}</view>

    <!-- 学习列表 -->
    <view class="study-list">
      <view 
        class="study-item" 
        v-for="(item, index) in currentCourse.lessons" 
        :key="index"
        @click="playLesson(index)"
      >
        <view class="lesson-info">
          <!-- 视频名称 -->
          <view class="lesson-name">{{ item.name }}</view>
          <!-- 学习状态 -->
          <view class="status-container">
            <view :class="['lesson-status', getStatusClass(item)]">
              <view v-if="item.completed">已完成</view>
              <view v-else-if="item.isLearning">学习中</view>
              <view v-else>未完成</view>
            </view>
          </view>
        </view>
        <!-- 时间条 -->
        <view v-if="item.isLearning || !item.completed" class="lesson-time">
          {{ formatTime(item.isLearning ? item.currentTime : '00:00') }}/{{ formatTime(item.totalTime) }}
        </view>
      </view>
    </view>

    <!-- 报名弹窗 -->
    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog 
        v-if="isReadyToSignup"
        mode="base"
        title="线上学习已完成"
        content="请确认是否报名参加线下学习"
        :before-close="true"
        @close="closePopup"
        @confirm="confirmSignup"
        confirmText="报名参加"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import uniPopup from '@/components/uni-popup/uni-popup.vue'
import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
import { list, getVideoDetail } from '/api/study.js'
import { getAllActivity, getActivityList } from '/api/activity.js'
import { getCarouselList } from '/api/carousel.js'

export default {
  components: {
    uniPopup,
    uniPopupDialog
  },
  data() {
    return {
      currentCourse: {
        title: '',
        videoUrl: '', 
        lessons: [] 
      },
      isLoading: true,
      isError: false,
      currentIndex: 0, // 当前播放的章节索引
      totalWatchedTime: 0,
      requiredWatchTime: 60 * 15,
      isReadyToSignup: false,
      videoContext: null, 
      lessonProgress: {}, // 记录每个视频的播放进度（秒）
      videoUrlPrefix: 'https://' // 视频URL协议头
    }
  },
  async onLoad(options) {
    const { videoId } = options 
    if (videoId) {
      await this.loadCourseData(videoId) 
    } else {
      uni.showToast({ title: '缺少视频ID', icon: 'none' })
    }
	 
	const sdkVersion = uni.getSystemInfoSync().SDKVersion;
	  console.log('小程序基础库版本:', sdkVersion);
	  
	  // 检查m3u8支持性（微信小程序特有）
	  if (uni.getSystemInfoSync().platform === 'wechat') {
	    console.log('微信小程序环境，支持m3u8格式');
	  }
  },
  methods: {
    async loadCourseData(videoId) {
      try {
        this.isLoading = true
        const res = await list({ videoId }) 
        const courseData = res.data
		console.log('courseData:', courseData)
		
        const activityRes = await getActivityList()
        const activityData = activityRes.data || [] 
        const firstActivity = activityData[0] || {} 
        const activityName = firstActivity.activityName || '默认活动名称'
        
        // 构建 lessons 数据（适配多张表关联）
        this.currentCourse = {
          title: activityName, 
          // 格式化视频URL
          videoUrl: this.formatUrl(courseData.url), 
          lessons: courseData.map(video => ({
            name: video.name,
            // 格式化每个课程的视频URL
            videoUrl: this.formatUrl(video.url), 
            currentTime: 0,
            totalTime: video.length,
            isLearning: false,
            completed: false
          }))
        }
      } catch (error) {
        console.error('数据加载失败:', error)
        this.isError = true
      } finally {
        this.isLoading = false
      }
    },
    
    // 格式化URL（添加协议头）
    formatUrl(url) {
      if (!url) return '';
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      return this.videoUrlPrefix + url;
    },
    
    async playLesson(index) {
      const lesson = this.currentCourse.lessons[index]
      
      // 验证视频URL有效性
      if (!lesson.videoUrl || !this.isValidUrl(lesson.videoUrl)) {
        uni.showToast({ 
          title: '视频地址无效，请联系管理员', 
          icon: 'none' 
        });
        return;
      }
      
      // 标记为“学习中”
      this.currentCourse.lessons.forEach((item, i) => {
        item.isLearning = i === index
        item.completed = item.completed || false 
      })
      // 更新当前播放索引
      this.currentIndex = index 
      // 加载视频地址
      this.currentCourse.videoUrl = lesson.videoUrl 
	  console.log('播放视频URL:', this.currentCourse.videoUrl)
      // 从缓存进度续播（无缓存则从头开始）
      const progress = this.lessonProgress[index] || 0 
      this.videoContext = uni.createVideoContext('videoPlayer') 
      this.videoContext.seek(progress) 
      this.videoContext.play() 
    },
    
    // 验证URL有效性
    isValidUrl(url) {
      if (!url) return false;
      return /^https?:\/\/.+$/.test(url);
    },
    
    // 监听视频播放进度变化
    handleTimeUpdate(e) {
      const currentTime = e.detail.currentTime
      const index = this.currentIndex
      // 记录当前章节的播放进度
      this.lessonProgress[index] = currentTime 
      // 累计总观看时长（可根据需求判断是否需要区分章节）
      this.totalWatchedTime += 1 
    },
    
    // 视频加载完成后，若有缓存进度则自动跳转
    handleVideoLoaded() {
      const index = this.currentIndex
      const progress = this.lessonProgress[index] || 0
      this.videoContext && this.videoContext.seek(progress)
    },
    
    // 视频错误处理
    handleVideoError(e) {
          console.error('视频错误详情:', e);
          this.isError = true;
          
          // 微信小程序video组件错误码参考：https://developers.weixin.qq.com/miniprogram/dev/component/video.html
          if (e.detail) {
            const { errCode, errMsg } = e.detail;
            
            if (errCode === 201) {
              uni.showToast({
                title: '视频格式不支持或URL无效',
                icon: 'none'
              });
            } else if (errCode === 202) {
              uni.showToast({
                title: '网络错误，请检查网络连接',
                icon: 'none'
              });
            } else if (errCode === 301) {
              uni.showToast({
                title: '视频加载超时，请重试',
                icon: 'none'
              });
            } else {
              uni.showToast({
                title: `视频加载失败: ${errMsg || '未知错误'}`,
                icon: 'none'
              });
            }
          } else {
            uni.showToast({
              title: '视频加载失败，请检查网络',
              icon: 'none'
            });
          }
        },
    // 去报名按钮点击事件（移除时间限制）
    handleSignup() {
      // 直接打开报名弹窗或进入页面
      uni.navigateTo({
        url: '/pages/activity/activity'
      });
    },
    
    // 关闭弹窗
    closePopup() {
      this.$refs.popup.close()
    },
    
    // 确认报名（保留弹窗确认逻辑，可根据需要删除）
    confirmSignup() {
      uni.showToast({
        title: '报名成功',
        icon: 'success',
        duration: 2000
      })
      this.$refs.popup.close()
      uni.navigateTo({
        url: '/pages/activity/activity'
      })
    },
    
    // 状态样式
    getStatusClass(item) {
      if (item.isLearning) {
        return 'learning-status'
      } else if (!item.completed) {
        return 'uncompleted-status'
      }
      return ''
    },
    
    // 时间格式化
    formatTime(time) {
      if (time === null || time === undefined) {
        return '00:00'
      }
      // 如果是数字类型，先转为秒数处理
      if (typeof time === 'number') {
        const m = Math.floor(time / 60)
        const s = time % 60
        return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
      }
      // 如果是字符串类型，尝试按 : 分割处理
      if (typeof time === 'string') {
        const parts = time.split(':')
        if (parts.length === 2) {
          const minutes = parts[0].padStart(2, '0')
          const seconds = parts[1].padStart(2, '0')
          return `${minutes}:${seconds}`
        }
      }
      // 其他异常情况，返回默认值
      return '00:00'
    }
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
}

.video-container {
  position: relative;
  width: 100%;
  height: 300px;
  background-color: #000;
}

.video-player {
  width: 100%;
  height: 100%;
}

.go-signup {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 5px 12px;
  background-color: #ff5722;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  z-index: 100;
}

/* 新增：加载和错误提示样式 */
.loading, .error-tip {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 99;
}

.error-tip {
  color: #ff5722;
}

/* 其他样式保持不变... */
.course-title {
  padding: 15px 20px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  border-bottom: 1px solid #f2f2f2;
}

.study-list {
  flex: 1;
  padding: 15px 20px;
}

.study-item {
  padding: 10px 0;
  border-bottom: 1px solid #f2f2f2;
}

.lesson-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.lesson-index {
  flex-shrink: 0;
  margin-right: 10px;
  color: #666;
}

.lesson-name {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.status-container {
  display: flex;
  align-items: center;
}

.lesson-status {
  font-size: 12px;
  color: #999;
  padding: 5px 8px;
  border-radius: 4px;
  margin-right: 5px;
}

.learning-status {
  border: 1px solid #ff5722;
  color: #ff5722;
}

.uncompleted-status {
  border: 1px solid #ccc;
  color: #999;
}

.lesson-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>